package com.rainszj.service.impl;

import com.rainszj.exception.MyNotFoundException;
import com.rainszj.mapper.BlogMapper;
import com.rainszj.pojo.dto.QueryBlog;
import com.rainszj.pojo.po.Blog;
import com.rainszj.pojo.po.BlogAndTag;
import com.rainszj.pojo.po.Tag;
import com.rainszj.pojo.po.User;
import com.rainszj.pojo.vo.*;
import com.rainszj.service.BlogService;
import com.rainszj.service.TagService;
import com.rainszj.utils.MarkdownUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author rainszj
 * 2020/3/16
 */
@Service
public class BlogServiceImpl implements BlogService {

    private final static Logger logger = LoggerFactory.getLogger(BlogServiceImpl.class);

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private TagService tagService;

    /**
     * 通过id获取要更新的博客
     *
     * @param id
     * @return
     */
    @Override
    public UpdateBlog getToUpdateBlogById(Long id) {
        return blogMapper.getToUpdateBlogById(id);
    }

    /**
     * 动态条件查询博客
     *
     * @param queryBlog
     * @return
     */
    @Override
    public List<BlogQueryResult> listQueryBlog(QueryBlog queryBlog) {
        // 选中推荐按钮，设置为 1
        String checked = "on";
        if (checked.equals(queryBlog.getRecommend())) {
            queryBlog.setRecommend("1");
        }

        return blogMapper.queryBlogByTitleOrTypeOrRecommend(queryBlog);
    }

    /**
     * 保存博客
     *
     * @param blog
     * @return
     */
    @Override
    public int saveBlog(Blog blog) {
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());
        blog.setViews(0L);
        int result = blogMapper.saveBlog(blog);

        List<Tag> tags = blog.getTags();
        BlogAndTag bat = null;
        for (Tag tag : tags) {
            bat = new BlogAndTag(tag.getId(), blog.getId());
            blogMapper.saveBlogAndTag(bat);
        }

        return result;
    }

    /**
     * 查询所有的博客
     *
     * @return
     */
    @Override
    public List<BlogQueryResult> listAdminBlog() {
        return blogMapper.listAdminBlog();
    }

    /**
     * 删除博客
     *
     * @param id
     * @return
     */
    @Override
    public int removeBlog(Long id) {
        // 删除成功
        if (blogMapper.removeBlogAndTag(id) > 0 && blogMapper.removeBlog(id) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 修改博客
     *
     * @param id
     * @param blog
     * @return
     */
    @Override
    public int updateBlog(Long id, UpdateBlog blog) {
        // 修改时间
        blog.setUpdateTime(new Date());
        List<Tag> tags = tagService.stringTagsToList(blog.getTagIds());
        BlogAndTag bat = null;
        // 没有选中标签，删除博客对应的所有标签
        if (tags.size() == 0) {
            blogMapper.removeBlogAndTag(id);
        } else {
            // 有选中的标签，进行修改
            for (Tag tag : tags) {
                BlogAndTag bt = tagService.queryBlogAndTag(tag.getId(), blog.getId());
                // BlogAndTag表中已存在 tagId，blogId
                if (bt == null) {
                    bat = new BlogAndTag(tag.getId(), blog.getId());
                    blogMapper.saveBlogAndTag(bat);
                }
            }
        }
        return blogMapper.updateBlog(id, blog);
    }

    /**
     * 查询首页展示的博客
     *
     * @return
     */
    @Override
    public List<IndexBlog> listIndexBlog() {
        return blogMapper.listIndexBlog();
    }

    /**
     * 获取最新发布的博客
     *
     * @param number
     * @return
     */
    @Override
    public List<LatestBlog> listLatestBlog(int number) {
        return blogMapper.listLatestBlog(number);
    }

    /**
     * 获取博客详情页
     *
     * @param id
     * @return
     */
    @Override
    public DetailedBlog getDetailedBlogById(Long id) {
        DetailedBlog detailedBlog = blogMapper.getDetailedBlogById(id);
        if (detailedBlog == null) {
            throw new MyNotFoundException("该博客不存在");
        }
        List<Tag> tags = tagService.stringTagsToList(detailedBlog.getTagIds());
        detailedBlog.setTags(tags);
        String content = detailedBlog.getContent();
        // 将 markdown 装换成 html
        detailedBlog.setContent(MarkdownUtils.markdownToHtmlExtensions(content));

        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User) subject.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            // 普通用户点击博客时，浏览次数 +1
            blogMapper.updateBlogViews(id);
        }

        return detailedBlog;
    }

    /**
     * 根据分类Id查询该分类下发布的博客
     *
     * @param id
     * @return
     */
    @Override
    public List<IndexBlog> getIndexBlogByTypeId(Long id) {
        List<IndexBlog> indexBlogs = blogMapper.getIndexBlogByTypeId(id);
        if (indexBlogs == null || indexBlogs.size() == 0) {
            throw new MyNotFoundException("该分类不存在");
        }
        return indexBlogs;
    }

    /**
     * 通过标签 Id 查询该标签下的发布的博客
     *
     * @param tagId
     * @return
     */
    @Override
    public List<IndexBlog> getIndexBlogByTagId(Long tagId) {
        List<IndexBlog> indexBlogs = blogMapper.getIndexBlogByTagId(tagId);
        if (indexBlogs == null || indexBlogs.size() == 0) {
            throw new MyNotFoundException("该标签不存在");
        }
        return indexBlogs;
    }

    @Override
    public List<IndexBlog> queryBlogByString(String queryStr) {
        return blogMapper.queryBlogByString(queryStr);
    }


    /**
     * 根据 Id 查询 Blog
     *
     * @param blogId
     * @return
     */
    @Override
    public Blog queryBlogById(Long blogId) {
        return blogMapper.queryBlogById(blogId);
    }

    /**
     * 博客归档
     *
     * @return
     */
    @Override
    public Map<String, List<ArchiveBlog>> archive() {
        List<String> years = blogMapper.queryGroupByYear();
        Map<String, List<ArchiveBlog>> map = new HashMap<String, List<ArchiveBlog>>();
        for (String year : years) {
            List<ArchiveBlog> blogs = blogMapper.queryBlogByYear(year);
            map.put(year, blogs);
        }

        return map;
    }

    /**
     * 查询博所有发布博客的数量
     *
     * @return
     */
    @Override
    public int countBlog() {
        return blogMapper.countBlog();
    }


}
